package com.hujinwen.esay.t1;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by joe on 2020/3/22
 * <p>
 * 1测试题
 */
public class Test_1 {

    /**
     * 自己的版本
     */
    static class Function1 {

        public int[] twoSum(int[] nums, int target) {
            int len = nums.length;
            for (int i = 0; i < len; i++) {
                for (int j = 0; j < len; j++) {
                    if (i == j) {
                        continue;
                    }
                    if (nums[i] + nums[j] == target) {
                        return new int[]{i, j};
                    }
                }
            }
            return null;
        }
    }

    /**
     * 参考别人的版本
     */
    static class Function2 {
        public int[] twoSum(int[] nums, int target) {
            final Map<Integer, Integer> cache = new HashMap<>();

            for (int i = 0; i < nums.length; i++) {
                int num = nums[i];
                int need = target - num;
                if (cache.containsKey(need)) {
                    return new int[]{cache.get(need), i};
                }
                cache.put(num, i);
            }

            throw new IllegalArgumentException("");
        }
    }

    public static void main(String[] args) {
        Function2 function = new Function2();

        int[] nums = {3, 3};
        int target = 6;

        int[] result = function.twoSum(nums, target);
        System.out.println();
    }

}
